import axios from 'axios'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { useUserStore } from '@/stores/user'
import router from '@/router'

// 创建axios实例
export const httpInstance = axios.create({
  baseURL: '/api',
  timeout: 5000
})

// axios请求拦截器
httpInstance.interceptors.request.use(config => {
  try {
    const userStore = useUserStore();
    const token = userStore.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
  } catch (e) {
    console.error('获取用户信息失败:', e);
    // 忽略
  }
  return config
}, e => Promise.reject(e))

// 响应拦截器
httpInstance.interceptors.response.use(
  res => {
    // 假设后端返回 { code, msg, data }
    if (res.data.code && res.data.code !== 0) {
      ElMessage({
        type: 'warning',
        message: res.data.msg || '业务异常'
      })
      // 主动抛出错误，让业务 catch
      return Promise.reject(res.data)
    }
    return res.data
  },
  e => {
    console.log('请求错误:', e);
    if(e.response?.status === 401) {
      //清除本地数据
      const userStore = useUserStore();
      userStore.clearUserInfo();

      // 跳转到登录页面，并记录当前地址
      router.push({
        path: '/login',
        query: { redirect: router.currentRoute.value.fullPath }
      })
      ElMessage.error('登录已过期，请重新登录')
    }
    return Promise.reject(e)
  }
)

export const get = (url, params = {}, config = {}) => {
  return httpInstance.get(url, { params, ...config })
}

export const put = (url, data = {}, config = {}) => {
  return httpInstance.put(url, data, config)
}

export const del = (url, config = {}) => {
  return httpInstance.delete(url, config)
}

export const post = (url, data = {}, config = {}) => {
  console.log('post调用', url, data)
  return httpInstance.post(url, data, config)
}
